<template>
  <div class="work-content-container">
    <!-- 头部操作区域 -->
    <div class="header-container">
      <!-- 刷新按钮 -->
      <div class="refresh-btn">
        <el-button type="primary" @click="fetchWorkList" :loading="loading" class="refresh-btn">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>

      <!-- 查询和日期选择区域 -->
      <div class="filter-area">
        <!-- 搜索框 -->
        <div class="search-combo">
          <el-input
            v-model="searchQuery"
            placeholder="输入关键词搜索"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
            class="search-input"
          />
          <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">
            查询
          </el-button>
        </div>

        <!-- 单独日期选择器 -->
        <div class="date-pickers">
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="开始日期"
            @change="handleDateChange"
            class="date-picker"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="结束日期"
            @change="handleDateChange"
            class="date-picker"
          />
        </div>
      </div>
    </div>

    <!-- 工作内容列表 -->
    <el-card class="work-list-card">
      <el-table
        :data="displayedWorkList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
        highlight-current-row
      >
        <el-table-column prop="username" label="用户" width="120">
          <template #default="{ row }">
            {{ row.username || '用户名未提供' }}
          </template>
        </el-table-column>

        <el-table-column prop="content" label="工作内容" min-width="200">
          <template #default="{ row }">
            {{ row.content || '暂无工作内容' }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" effect="light">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="comment" label="审核评论" width="200">
          <template #default="{ row }">
            {{ row.comment || '暂无评论' }}
          </template>
        </el-table-column>

        <el-table-column prop="attachment" label="附件" width="150" align="center">
          <template #default="{ row }">
            <el-link
              v-if="row.attachment"
              :href="`${$apiBaseUrl}/download/docdownload/${row.id}`"
              type="primary"
              :underline="false"
            >
              下载附件
            </el-link>
            <el-tag v-else type="info" effect="plain">无附件</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getWorkContents } from '@/api/workcontent.js'
import { useUserStore } from '@/stores/user'
import { Search } from '@element-plus/icons-vue'

const workList = ref([]) // 当前页显示的数据
const allData = ref([]) // 所有原始数据
const filteredData = ref([]) // 过滤后的数据(不含分页)
const loading = ref(false)
const searchQuery = ref('')
const startDate = ref('')
const endDate = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filteredTotal = ref(0)

// 获取工作列表
const fetchWorkList = async () => {
  try {
    loading.value = true
    const userStore = useUserStore()
    const response = await getWorkContents({
      departmentId: userStore.user.departmentId,
      userId: userStore.user.id,
    })

    allData.value = response.data.data || []
    total.value = allData.value.length
    applyFilters()
    ElMessage.success('工作列表数据获取成功！')
  } catch (error) {
    ElMessage.error('获取工作列表失败')
    console.error('获取工作列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 显示的数据(当前页的数据)
const displayedWorkList = computed(() => {
  return workList.value
})

// 应用所有过滤条件
const applyFilters = () => {
  // 1. 先应用搜索和日期过滤
  filteredData.value = filterData(allData.value)
  filteredTotal.value = filteredData.value.length

  // 2. 然后应用分页
  applyPagination()
}

// 数据过滤逻辑
const filterData = (data) => {
  let result = [...data]

  // 日期过滤 - 支持单独选择开始或结束日期
  if (startDate.value || endDate.value) {
    result = result.filter((item) => {
      const itemDate = new Date(item.createdAt)
      const start = startDate.value ? new Date(startDate.value) : null
      const end = endDate.value ? new Date(endDate.value) : null

      // 仅开始日期
      if (start && !end) return itemDate >= start
      // 仅结束日期
      if (!start && end) return itemDate <= end
      // 开始和结束日期
      if (start && end) return itemDate >= start && itemDate <= end

      return true
    })
  }

  // 模糊搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(
      (item) =>
        (item.content && item.content.toLowerCase().includes(query)) ||
        (item.username && item.username.toLowerCase().includes(query)) ||
        (item.comment && item.comment.toLowerCase().includes(query)),
    )
  }

  return result
}

// 应用分页
const applyPagination = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  workList.value = filteredData.value.slice(start, end)
}

// 日期变化处理
const handleDateChange = () => {
  currentPage.value = 1
  applyFilters()
}

// 模糊搜索处理
const handleSearch = () => {
  currentPage.value = 1
  applyFilters()
}

const handleSearchClear = () => {
  searchQuery.value = ''
  applyFilters()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  applyPagination()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  applyPagination()
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '通过',
    rejected: '驳回',
  }
  return statusMap[status] || status
}

// 根据状态返回对应的标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
  }
  return typeMap[status] || 'info'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 组件挂载时获取工作列表
onMounted(() => {
  fetchWorkList()
})
</script>

<style scoped>
.work-content-container {
  padding: 20px;
}


.search-input {
  flex: 1; /* 让输入框占据剩余空间 */
}


/* 查询按钮样式 */
.search-combo {
  width: 65%; /* 调整为合适的宽度 */
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  gap: 10px;
}

.search-btn {
  height: 40px;
  width: 80px; /* 固定按钮宽度 */
  padding: 0;
  border-radius: 0 6px 6px 0;
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 按钮点击效果 */
.search-btn:active {
  background-color: #3a8ee6;
  transform: translateY(0);
}

/* 刷新按钮样式 */
.refresh-btn {
  background-color: #409eff;
  border: none;
  color: white;
  border-radius: 6px; /* 圆角 */
  display: inline-flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  float: right;
}

/* 悬停效果 */
.refresh-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px); /* 轻微上浮 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); /* 悬停时阴影加深 */
}

/* 筛选区域 */
.filter-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-width: 800px;
  padding-bottom: 10px;
}

/* 日期选择器区域 */
.date-pickers {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-picker {
  width: 180px;
}

.date-separator {
  color: var(--el-text-color-secondary);
  padding: 0 8px;
}

/* 按钮样式 */
.refresh-btn,
.search-btn {
  height: 32px;
}

/* 头部操作区布局 */
.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 20px;
}

/* 统一控件高度 */
.el-date-editor,
.el-button {
  height: 40px;
}

.work-list-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.el-table {
  margin-top: 10px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(.cell) {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .search-combo,
  .el-date-editor {
    width: 100%;
  }
}
</style>
